<?php

require_once(dirname(dirname(dirname(dirname(__FILE__)))).'/appconf.php');
  
require_once "CMS.class.php";

$local_config = array(
    'this_cgi'       => 'cms/builder/product/reports.php',
    'tmpl'           => array('base_path' => 'cms/builder/product/reports/'), # full path = $this->param('TMPL').$
    'database'       => '',
    'table'          => 'product_reports',
    'cms_auth_group'  => 'User Data',
    '#MESSAGE#'      => array(),
);

class cms_builder_product_reports extends CMS{

  function setup(){
    $this->run_modes('list',
                     'edit',
                     
                     'update', 
                     'mupdate',
                     'view', 
                     
                     'add', 
                     'madd', 
                     'showadd', 'edit_after_add',
                     
                     'showdel', 
                     'del', 
                     
                     'showsearch','search','clearsearch',
                     
                     'showsetting', 'setting',
                     
                     'ajax_update_field',
                     
                     'trap'
                    );
    $this->start_mode('list');
    $this->set_path_info_position(array('oid'=>1, 'id'=>2));
    parent::setup();
  }

  function cgiapp_prerun($rm=''){
    
    parent::cgiapp_prerun($rm); # login, targeted to run CMS_Login.class.php 
    
  }

  function cgiapp_postrun(&$body){
    parent::cgiapp_postrun($body);

    $a_js = array();
    if (method_exists($this, 'inject_js') && count($this->inject_js()) > 0){ // some old CMS.class.php don't support yet
    	$a_js = $this->inject_js();
    }
    
	$oid = $this->get_param('pq', 'oid');
	$dbh_r = $this->db_connect('read');
  $label = db_select_one($dbh_r, "select cname from product where id=?", array($oid));
  $label = str_replace(array("\n","\r"), '', $label);
     $label = html_link('產品', '/cms/builder/product.php').' - '.$label; 
  
	if (empty_string($label)){
		$label = ' <span class="pswarning">Unknown &gt; </span>';
	} else {
		$label = $label.' &gt; ';
	}
	array_push($a_js, "$('#parent_key_label').html('$label');");

  //	
    
    $login = $this->get_cms_username();
    if (!empty_string($login)){
      array_push($a_js, "\$('#login').html('Hi $login!  <a href=\"/cms/builder/logout.php\" style=\"color:red;\">Logout</a>');");
    }
  
    if ($this->header_type() == 'redirect'){
      return;	
    }
    
    $a_msg = array();
    $a_current_msg = $this->message();
    $a_session_msg = $this->get_message_from_session();
    foreach ($a_session_msg as $msg){
    	array_push($a_msg, $msg);
    }
    foreach ($a_current_msg as $msg){
    	array_push($a_msg, $msg);
    }
    
    $message = '';
    if (count($a_msg)>0){
      $message = implode('<BR>', $a_msg);
      array_push($a_js, "\$(document).ready(function(){ $(\"#dialog-modal\").dialog({height: 140,modal: true});  });");
    }

    if (count($a_js) > 0){
      $temp = "<script>".implode('', $a_js)."</script>";
      if ($message != ''){
        $temp .= html_dialog('Notice', $message);
      }
      $body = preg_replace('/(<!--POSTRUNJS-->)/', $temp, $body, 1);
      
    }
    
  }

#no no login

  // some
  function trap(){
	  $a_msg = $this->message();
	  $message = '';
	  if (count($a_msg)>0){
	    $message = implode('<BR>', $a_msg);
	    $this->tmpl_assign('title', 'Application Error');
	    $this->tmpl_assign('body',  $message);
  	  return $this->load_tmpl($this->param('TMPL'),  'error.html');
    }
    return '';
  }

  function action_list(){
  	if (! $this->user_can('list') ) return $this->trap();
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    # on_start_list() *removed* - give it a chance to modify FK and TOP

    $dbh_r = $this->db_connect('read');
    $list_control = $this->update_listing_ordering();
    $sqlstr = 'SELECT * FROM '.$this->param('table').
              $this->listing_condition();
    
    $agegroup_type = $this->create_lookup_array($dbh_r, "agegroup_type", 'id', "cname", ' where status=1'); 
    $product_reports_accept_grade_type = $this->create_lookup_array($dbh_r, "product_reports_accept_grade_type", 'id', "cname", 'where status=1'); 
    $product_reports_reject_reason_type = $this->create_lookup_array($dbh_r, "product_reports_reject_reason_type", 'id', "cname", 'where status=1'); 
    $h_feature = array(
      'agegroup'         => array('h:label',         'agegroup',        $agegroup_type ,array()),
      'grade'            => array('h:label',         'grade',           $product_reports_accept_grade_type ,array()),
      'reject_reason'    => array('h:label',         'reject_reason',   $product_reports_reject_reason_type ,array()),
      'is_accept'        => array('ny:label',        'is_accept',       ),
      'is_publish'       => array('ny:label',        'is_publish',      ),
      '#ROW_FUNCTION#' => 'list_row_function',
      
      '#MULTIPLE#' =>1,
      '#PAGESIZE#' => 20,
      '#PAGELIST#' => '1,2,3',
      '#PAGE#'     => $this->get_param('q', 'page', 1, 'int'),
      '#GET_SELECTED_ID#' => 1,
      '#EXTRAQUERYSTR#' => "&oid=$oid"
      );
    list($list_data, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);

	  if (count($list_data) == 0){

      $this->message('No data.');
	  }

    $this->tmpl_assign('oid', $oid);
    
    $this->tmpl_assign('user_permission', $this->get_user_permission());
    $this->tmpl_assign('list_control', $list_control);

    $a_search_cond = $this->s_param('cms_builder_product_reports#'.'SEARCH_COND');
    $is_search = empty($a_search_cond)  ? 0: 1;

    $this->tmpl_assign('title_noun', $is_search > 0 ? 'Search Result of' : 'List of');
    $this->tmpl_assign('clear_search_link', $is_search > 0 ? html_link(' [Clear Search Result]', $this->self_url(array('action'=>'clearsearch','oid'=>$oid))) : '');
    $this->tmpl_assign('list_data', $list_data);
    $this->tmpl_assign('pagelist', $a_pagelist);
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    
    return $this->load_action_tmpl('list');
  }

  /*list action row function
   *  this function will run first when processing the row
   */
  function list_row_function($dbh_r, $h_row){    
    $mid = $h_row['mid'];
    $well= $h_row['well'];

    $member = getModel('CMS_Member');
    $member_blacklist = $member->blacklisted($mid);
    if($member_blacklist == 1){
         $member_blacklist = '<br />已列入黑名單';
    }else{
         $member_blacklist = '';
    }

    $report = getModel('CMS_Report');
    return array(
      'mid'        => $member->basic_info($mid).'<br />'.$member_blacklist,
      'well'       => $report->rate_mapping($well),
      );
  }

# in action_list, it should include this feature.
# $h_feature = array('#ROW_FUNCTION#' => 'ist_row_feature');

  function update_listing_ordering(){
  	$a_allowed_sorting_field = array();
  	if (count($a_allowed_sorting_field) == 0){
  		return array();
  	}
  	$sortbyfield = $this->s_param('cms_builder_product_reports#'.'sortby');
    #echo $sortbyfield;
    $a_sortbyfield = explode(',', $sortbyfield);
    $h_sortbyfield = array();
    foreach ($a_sortbyfield as $fieldname_order){
    	$a_temp = explode(' ', $fieldname_order);
    	$field = $a_temp[0];
    	$order = isset($a_temp[1])?$a_temp[1]:'';
    	#echo 'F['.$field.'] or['.$fieldname_order.']';
      $h_sortbyfield[$field]= $order;
    }
    
    $list_control = array();
    $a_result = array();
    $count = 0;
  	foreach ($a_allowed_sorting_field as $field){
  	  $sort_order=$this->get_q('sort_'.$field, '');
  	  if ($sort_order == ''){
  	  	if (isset($h_sortbyfield[$field])){
  	    	#echo "{".$h_sortbyfield[$field].'}';
  	  	  $sort_order =  $h_sortbyfield[$field];
     	  } else {
     	  	$sort_order = 'none';
     	  }	
  	  }
  	  
  	  if ($sort_order == 'none' || $sort_order == ''){
        $list_control['sort_'.$field] = html_img('/cms/images/ico/up_down_arrow.gif', '?sort_'.$field.'=desc');
        #array_push ($a_result, $field.' none');
        #echo 'list_control none sort_ '.$field;
  	  } elseif ($sort_order == 'desc'){
  	  	$list_control['sort_'.$field] = html_img('/cms/images/ico/down_arrow.gif', '?sort_'.$field.'=asc');
  	  	array_push ($a_result, $field.' desc');
  	  	#echo 'list_control down sort_ '.$field;
  	  } elseif ($sort_order == 'asc'){
  	  	$list_control['sort_'.$field] = html_img('/cms/images/ico/up_arrow.gif', '?sort_'.$field.'=none');
     	  array_push ($a_result, $field.' asc');
     	  #echo 'list_control up sort_ '.$field;
      }
  	  
  	}
  	
  	$temp = implode(',',$a_result);
  	#echo $temp.']';
  	$this->s_param('cms_builder_product_reports#'.'sortby', $temp);
  	return $list_control;
  }

  function listing_condition(){
    $a_where = array();

    array_push($a_where, "oid='".$this->get_param('pq','oid',0,'int')."'", 'and');

    $session_show_all_status = $this->s_param('cms_builder_product_reports#'.'SETTING_SHOWALLSTATUS');
    switch($session_show_all_status){
      case 'status_all':
        break;
      case 'status_0':
        array_push($a_where, "status=0", "and");
        break;
      case 'status_2':
        array_push($a_where, "status=2", "and");
        break;
      case 'status_none': # no status field
        break;
      default:
        array_push($a_where, "status>=1", "and");
        break;
    }	

    $a_search_condition = $this->s_param('cms_builder_product_reports#'.'SEARCH_COND');
    if (is_array($a_search_condition) && !empty($a_search_condition)){
      $a_where = array_merge($a_where, $a_search_condition);
    }

#    #array_push($a_where, "");#
#
#    $a_order = array();
#    $sortbyfield = $this->get_param('s','sortby', 'id');
#    $sortorder   = $this->get_param('s','sortorder', '');#
#
#    $a_sortbyfield = explode(',', $sortbyfield);
#    $a_sortorder   = explode(',', $sortorder);
#
#    foreach ($a_sortbyfield as $sortbyfield){
#      $sortorder = array_shift($a_sortorder);
#
#      array_push($a_order, "$sortbyfield $sortorder");
#   }

    $sortby = $this->s_param('cms_builder_product_reports#'.'sortby');
    if ($sortby == ''){
    	$sortby = ' sequence, addtime';
    }

    $final_str = '';
    if (count($a_where) > 0){
      array_pop($a_where);
      $final_str = ' where '.implode(' ', $a_where);
    }
    #if (count($a_order) > 0){
    #  $final_str .= ' order by '.implode(' and ', $a_order);
    #}
    $final_str .= ' order by '.$sortby;
    
    return $final_str;
  }

  function action_edit($id=null){
    if (! $this->user_can('edit') ) return $this->trap();
    if ($id === null){
       $id = $this->get_param('pq','id',  0, 'int');
    }
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    if ($id == 0
      || $oid == 0
      ) throw new CgiappErrorException(100, __METHOD__.' Invalid Parameter!');
    
    $dbh_r = $this->db_connect('read');

    $sqlstr = 'SELECT * FROM '.$this->param('table')." where id=".$id;
    
    $agegroup_type = $this->create_lookup_array($dbh_r, "agegroup_type", 'id', "cname", ' where status=1'); 
    $product_reports_accept_grade_type = $this->create_lookup_array($dbh_r, "product_reports_accept_grade_type", 'id', "cname", 'where status=1'); 
    $product_reports_reject_reason_type = $this->create_lookup_array($dbh_r, "product_reports_reject_reason_type", 'id', "cname", 'where status=1'); 
    $cms_user = $this->create_lookup_array($dbh_r, "cms_user", 'id', "name", 'where status=1'); 
    $h_feature = array(
      
      '#ROW_FUNCTION#' => 'edit_row_function',      
      'oid'              => array('f:func',          'oid',             'html_fix_edit_text'),
      'mid'              => array('f:func',          'mid',             'html_fix_edit_text'),
      'title'            => array('f:func',          'title',           'html_fix_edit_text'),
      'agegroup'         => array('h:list',          'agegroup',        $agegroup_type ,array()),
      'body'             => array('f:func',          'body',            'html_fix_edit_text'),
      'likes'            => array('f:func',          'likes',           'html_fix_edit_text'),
      'well'             => array('f:func',          'well',            'html_fix_edit_text'),
      'category_score1'  => array('f:func',          'category_score1', 'html_fix_edit_text'),
      'category_score2'  => array('f:func',          'category_score2', 'html_fix_edit_text'),
      'category_score3'  => array('f:func',          'category_score3', 'html_fix_edit_text'),
      'category_score4'  => array('f:func',          'category_score4', 'html_fix_edit_text'),
      'fb_share_num_base' => array('f:func',          'fb_share_num_base', 'html_fix_edit_text'),
      'likes_num_base'   => array('f:func',          'likes_num_base',  'html_fix_edit_text'),
      'category_score5'  => array('f:func',          'category_score5', 'html_fix_edit_text'),
      'category_score6'  => array('f:func',          'category_score6', 'html_fix_edit_text'),
      'category_score7'  => array('f:func',          'category_score7', 'html_fix_edit_text'),
      'category_score8'  => array('f:func',          'category_score8', 'html_fix_edit_text'),
      'is_valid'         => array('f:func',          'is_valid',        'html_fix_edit_text'),
      'discuz_pid'       => array('f:func',          'discuz_pid',      'html_fix_edit_text'),
      'priority'         => array('f:func',          'priority',        'html_fix_edit_text'),
      'grade'            => array('h:list',          'grade',           $product_reports_accept_grade_type ,array()),
      'reject_reason'    => array('h:list',          'reject_reason',   $product_reports_reject_reason_type ,array()),
      'is_accept'        => array('ny:radio',        'is_accept',       ),
      'is_publish'       => array('ny:radio',        'is_publish',      ),
      'addedby'          => array('h:label',         'addedby',         $cms_user ,array()),
      'modifiedby'       => array('h:label',         'modifiedby',      $cms_user ,array()),
      'approvedby'       => array('h:label',         'approvedby',      $cms_user ,array()),
      'status'           => array('status:radio',    'status',          ),
                       );
    
    if ( $this->user_can('approve', 1) ){
    	$h_feature['status'] = array('status:radio',    'status',          );
    } else {
    	$h_feature['status'] = array('status:label',    '',          );
    }	

    list($h_row, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);
    
    $this->audit_log('edit', $id);
    
    $this->tmpl_assign('oid', $oid);
    
    $this->tmpl_assign('edit_data', $h_row[0]);
    
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('edit');
  }

  /*edit action row function
   *  this function will run first when processing the row
   */
  function edit_row_function($dbh_r, $h_row){   
	$product = getModel('Model_CMS_Product');
        $id = $h_row['id'];  
        $oid = $h_row['oid'];
	
		$options = db_select_one($dbh_r, 'select vote_option from product where id=?', $oid);
		
		$a_option = explode(',', $options);
		
		for ($i=0; $i<count($a_option); $i++){
			$a_option[$i] = db_select_one($dbh_r, 'select cname from product_vote_option where id=?', $a_option[$i]);
		}

		$a_category_name = array();
		for ($i=0; $i<count($a_option); $i++){
			$a_category_name['category_name'.($i+1)] = $a_option[$i];

		}

	$return  = array(
	'content_view'        => $product->get_report_content($id),
	'category_scores'	=>	$product->get_report_category_scores($id, $oid)
	);
	
	return  array_merge($return, $a_category_name);
  }

  function action_view(){
    if (! $this->user_can('view') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    if ($id == 0
      || $oid == 0
      ) throw new CgiappErrorException(100, __METHOD__.' Invalid Parameter!');

    $dbh_r = $this->db_connect('read');

    $sqlstr = 'SELECT * FROM '.$this->param('table')." where id=".$id;
    
    $agegroup_type = $this->create_lookup_array($dbh_r, "agegroup_type", 'id', "cname", ' where status=1'); 
    $product_reports_accept_grade_type = $this->create_lookup_array($dbh_r, "product_reports_accept_grade_type", 'id', "cname", 'where status=1'); 
    $product_reports_reject_reason_type = $this->create_lookup_array($dbh_r, "product_reports_reject_reason_type", 'id', "cname", 'where status=1'); 
    $cms_user = $this->create_lookup_array($dbh_r, "cms_user", 'id', "name", 'where status=1'); 
    $h_feature = array(
      '#ROW_FUNCTION#' => 'view_row_function',
      'agegroup'         => array('h:label',         'agegroup',        $agegroup_type ,array()),
      'grade'            => array('h:label',         'grade',           $product_reports_accept_grade_type ,array()),
      'reject_reason'    => array('h:label',         'reject_reason',   $product_reports_reject_reason_type ,array()),
      'is_publish'       => array('ny:label',        'is_publish',      ),
      'addedby'          => array('h:label',         'addedby',         $cms_user ,array()),
      'modifiedby'       => array('h:label',         'modifiedby',      $cms_user ,array()),
      'approvedby'       => array('h:label',         'approvedby',      $cms_user ,array()),
      'status'           => array('status:label',    'status',          ),
                        );

    list($h_row, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);
    $this->audit_log('view', $id);
    
    $this->tmpl_assign('oid', $oid);
    
    $this->tmpl_assign('view_data', $h_row[0]);
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('view');
  }

  /*  view action row function
   *  this function will run first when processing the row
   */
  function view_row_function($dbh_r, $h_row){    
	$product = getModel('Model_CMS_Product');
        $id = $h_row['id'];  
        $oid = $h_row['oid'];  
	
	return array(
	'content_view'        => $product->get_report_content($id),
	'category_scores'	=>	$product->get_report_category_scores($id, $oid)
	);
  }

  function action_update(){
    if (! $this->user_can('edit') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    if ($id === false
      || $oid == 0
      ) throw new CgiappErrorException(100, __METHOD__.' Invalid Parameter!');
    
    $dbh_w    = $this->db_connect('write');
    $original_status = db_select_one($dbh_w, 'select status from '.$this->param('table').' where id=?', $id);

    $h_feature = array(

    );
    $changed = $this->update_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);
    $upload_changed = 0;
    
    if ($changed > 0 || $upload_changed > 0){
      db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW(),modifiedby=? where id=?", array($this->get_cms_userid(),$id)); 
      
      $this->audit_log('update', $id);
    }
    
    $new_status      = $this->get_q('status');
    if ($original_status != 0 && $new_status == 0){
      $this->on_after_del(array('oid'=>$oid), $id);
    }
   	
  if ($changed > 0  || $upload_changed > 0){
    $this->on_after_add_and_update(array('oid'=>$oid), $id);
  }  
  
    if ($this->get_q('subaction') == 'edit_after_update'){
      return $this->action_edit($id);
    }
    return  $this->cms_redirect_default_action( array('oid'=>$oid) );
  }

/*
 * $this->on_after_add_and_update(array('oid'=>$oid, 'topid'=>$topid));
 *  oid, topid may be unavailable
 * $id: id of record just added
 */
function on_after_add_and_update($h_param, $id){
  // $oid = $param['oid'];

  $dbh_w = $this->db_connect('write');


   list($id, $oid, $mid, $is_accept, $is_points_award, $priority) = db_selectrow_array($dbh_w, 'select id, oid, mid, is_accept, is_points_award, priority from '.$this->param('table').' where id=? and status=1', $id);
     
   $product_name = db_select_one($dbh_w, 'select name from product where id=?', $oid);

   
   $success = file_get_contents($this->param('CGI_URL')."/product.php?action=approveReport&pid=$oid&rid=$id&key=".md5($oid.$id."imoreHK"));

   if(!$success){
      $this->message("Update failed !");
   }

	$count = db_select_one($dbh_w, 'select count(*) from member_application where rid=? and status=1', $id);
	

	$points = getModel('CMS_Points');
	//count > 0 ===> report, else 心得
	if($count > 0){
	  if($is_accept == 0){
		if($is_points_award == 1){
			//deduct
			$points->points_record($mid, "reject_report", str_replace("[產品名稱]", $product_name,REJECT_REPORT_LANG));
			db_do($dbh_w, 'update '.$this->param('table').' set is_points_award=0 where id=?', $id);
		}
	  }else{
		if($is_points_award == 0){
			//add
			$points->points_record($mid, "submit_report", str_replace("[產品名稱]", $product_name,SUBMIT_REPORT_LANG));
			db_do($dbh_w, 'update '.$this->param('table').' set is_points_award=1 where id=?', $id);
			
			$a_rid = db_selectcol_array($dbh_w, 'select rid from member_application where product=? and status=1', $oid);
			$approved_report_num = 0;
			foreach($a_rid as $rid){
				$approved = db_select_one($dbh_w, 'select is_accept from '.$this->param('table').' where id=?', $rid);
				if($approved ==1){
					$approved_report_num++;
				}
				if($approved_report_num == 3)
					continue;
			}
			if($approved_report_num <3){
				$points->points_record($mid, "become_report_3rd", str_replace("[產品名稱]", $product_name,SUBMIT_REPORT_LANG));
			}
		}
	  }
	}
  
  $sequence =  65535-$priority;
  
  db_do($dbh_w, 'update '.$this->param('table').' set sequence=?, lastmodify=NOW() where id=? and status=1', array($sequence, $id));
}

  function action_mupdate(){
    if (! $this->user_can('edit') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    $dbh_w  = $this->db_connect('write');
    
    $h_feature = array(
    
    );
    
    //$this->mupdate_modify_feature(\%feature) if ($this->can('mupdate_modify_feature'));

    $a_changed = $this->update_table_multiple_row($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    $a_id = $this->q_param('id');
    foreach ($a_id as $id){
      $upload_changed = 0;
      
      if ($upload_changed > 0 && !in_array($id, $a_changed)){    
         array_push($a_changed, $id);
       } 

    }

    if (count($a_changed)>0){
      $changed = implode(',' , $a_changed);
      db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW(),modifiedby=? where id in ($changed)", array($this->get_cms_userid()));       
      $this->audit_log('update', $changed);
    }

    return $this->cms_redirect_default_action(array('oid'=>$oid));
  }
    
  function action_showadd(){
    if (! $this->user_can('add') ) return $this->trap();
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    if ($oid == 0) throw new CgiappErrorException(100,  __METHOD__.'Invalid Parameter');

    $dbh_r = $this->db_connect('read');

    $agegroup_type = $this->create_lookup_array($dbh_r, "agegroup_type", 'id', "cname", ' where status=1'); 
    $product_reports_accept_grade_type = $this->create_lookup_array($dbh_r, "product_reports_accept_grade_type", 'id', "cname", 'where status=1'); 
    $product_reports_reject_reason_type = $this->create_lookup_array($dbh_r, "product_reports_reject_reason_type", 'id', "cname", 'where status=1'); 
    $h_feature = array(
      
      'agegroup'         => array('h:list',          'agegroup',        $agegroup_type ,array()),
      'grade'            => array('h:list',          'grade',           $product_reports_accept_grade_type ,array()),
      'reject_reason'    => array('h:list',          'reject_reason',   $product_reports_reject_reason_type ,array()),
      'is_accept'        => array('ny:radio',        'is_accept',       ),
      'is_publish'       => array('ny:radio',        'is_publish',      ),
      );
    $h_default_value = array(
      'oid' => '',
      'mid' => '',
      'title' => '',
      'agegroup' => '',
      'content_json' => '',
      'body' => '',
      'likes' => '',
      'well' => '',
      'category_scores' => '',
      'category_name1' => '',
      'category_score1' => '',
      'category_name2' => '',
      'category_score2' => '',
      'category_name3' => '',
      'category_score3' => '',
      'category_name4' => '',
      'category_score4' => '',
      'fb_share_num_base' => '0',
      'likes_num_base' => '0',
      'category_name5' => '',
      'category_score5' => '',
      'category_name6' => '',
      'category_score6' => '',
      'category_name7' => '',
      'category_score7' => '',
      'category_name8' => '',
      'category_score8' => '',
      'is_valid' => '',
      'discuz_pid' => '',
      'priority' => '10',
      'grade' => '',
      'reject_reason' => '',
      'is_accept' => '',
      'is_publish' => '',
      );
                 
    $showadd_data = $this->process_showadd_feature($dbh_r, $h_feature, $h_default_value);

    $this->tmpl_assign('oid', $oid);
    
    $this->tmpl_assign('showadd_data', $showadd_data);
    
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('showadd');
  }

  function action_add(){
    if (! $this->user_can('add') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    $dbh_w    = $this->db_connect('write'); # db_connect default is readonly

    $h_feature = array(
    'addtime'=>'skip','lastmodify'=>'skip', 

    );
    $changed = $this->add_to_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    if ($changed > 0 ){
      $id = db_last_insert_id($dbh_w);
      db_do($dbh_w, "update ".$this->param('table')." set addtime=NOW(),lastmodify=NOW(),addedby=?,modifiedby=? where id=?", array($this->get_cms_userid(),$this->get_cms_userid(),$id)); 
      
    }
    $upload_changed = 0;
     
    $this->audit_log('add', $id);

  if ($changed > 0  || $upload_changed > 0){
    $this->on_after_add_and_update(array('oid'=>$oid), $id);
  }  
  
  if ($this->get_q('subaction') == 'edit_after_add'){
    return $this->action_edit($id);
  }
  
  if ($this->get_q('subaction') == 'showadd_after_add'){
	  return $this->action_showadd();
	}
  
    return $this->cms_redirect_default_action(array('oid'=>$oid));
  }

  function action_madd(){
    if (! $this->user_can('add') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    $dbh_w       = $this->db_connect('write');
    $h_feature = array(
    'addtime'=>'skip','lastmodify'=>'skip', 
    #'addtime' => 'addtime', 'lastmodify' => 'lastmodify',
    
    );
    $changed   = $this->add_to_table_multiple_row($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    if (count($a_changed) > 0){
      foreach ($a_changed as $id){
        $row_affected = $dbh_w->exec("update ".$this->param('table')." set lastmodify = NOW() where id = '$id'") ;
      }
    }
    
		if (count($a_changed) > 0){
		  $changed_id = implode(',', $a_changed);
	    $this->audit_log('madd', $changed_id);
	  }
	
    return $this->cms_redirect_default_action(array('oid'=>$oid));
  }

  /*
   *
   */
  function action_del(){
    if (! $this->user_can('del') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    $dbh_w  = $this->db_connect('write');
    $h_param = array(

    '#DELETE_MODE#' => 'hidden'
   );
    $this->delete_from_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_param);
    
    db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW(),modifiedby=? where id=?", array($this->get_cms_userid(),$id)); 
    $this->audit_log('del', 'hidden-'.$id);
    $this->on_after_del(array('oid'=>$oid), $id);
    return $this->cms_redirect_default_action(array('oid'=>$oid));
  }

/*
 * $this->on_after_del(array('oid'=>$oid, 'topid'=>$topid));
 *  oid, topid may be unavailable
 * $id: id of record just deleted.
 */
function on_after_del($h_param, $id){
  // $oid = $param['oid'];

   $dbh_r = $this->db_connect();
   $oid = db_select_one($dbh_r, 'select oid from '.$this->param('table').' where id=?', $id);

   $success = file_get_contents($this->param('CGI_URL')."/product.php?action=approveReport&pid=$oid&rid=$id&key=".md5($oid.$id."imoreHK"));

   if(!$success){
      $this->message("Update report failed calculation");
   }
}

  function action_mdel(){
    if (! $this->user_can('del') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    # input check
    $a_selected   = array();
    $a_keys      = $this->get_q('mselected_id'); // we may support this field as configurable so that not only cms can use
    if (is_array($a_keys) ){
	    foreach ($a_keys as $row_key){    	
	    	if (ctype_digit($row_key)){
	        array_push($a_selected, $row_key);
	      }
	    }
    }
    if (count($a_selected) == 0){
    	$this->message('Please select the ID for records to be deleted!');
      return $this->cms_redirect_default_action(array('oid'=>$oid));    	
    }
    # end input check
    
    $dbh_w  = $this->db_connect('write');
    $h_param = array(
      
      '#DELETE_MODE#' => 'hidden'
      );
    $a_changed = $this->delete_multiple_from_table($dbh_w, $this->param('table'),'HTTP_POST', $h_param);
    
 		if (count($a_changed) > 0){
		  $changed_id = implode(',', $a_changed);
	    db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW(),modifiedby=? where id in ($changed_id)", array($this->get_cms_userid())); 
	  }

		if (count($a_changed) > 0){
		  $changed_id = implode(',', $a_changed);
	    $this->audit_log('mdel', 'hidden-'.$changed_id);
	  }
	
    return $this->cms_redirect_default_action(array('oid'=>$oid));
  }

  function action_help(){
  	#if (! $this->user_can('help') ) return $this->trap();
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
  	return $this->load_action_tmpl('help');
  }
/**HELP:__HELP**/

  function action_showsearch(){
    if (! $this->user_can('list') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    if ($oid == 0) throw new CgiappErrorException(100,  __METHOD__.'Invalid Parameter');

    $dbh_r = $this->db_connect('read');
    $h_default_value = array(
      'oid'=>'',# add session support later
      'mid'=>'',# add session support later
      'title'=>'',# add session support later
      'agegroup'=>'',# add session support later
      'content_json'=>'',# add session support later
      'body'=>'',# add session support later
      'likes'=>'',# add session support later
      'well'=>'',# add session support later
      'category_scores'=>'',# add session support later
      'category_name1'=>'',# add session support later
      'category_score1'=>'',# add session support later
      'category_name2'=>'',# add session support later
      'category_score2'=>'',# add session support later
      'category_name3'=>'',# add session support later
      'category_score3'=>'',# add session support later
      'category_name4'=>'',# add session support later
      'category_score4'=>'',# add session support later
      'fb_share_num_base'=>'0',# add session support later
      'likes_num_base'=>'0',# add session support later
      'category_name5'=>'',# add session support later
      'category_score5'=>'',# add session support later
      'category_name6'=>'',# add session support later
      'category_score6'=>'',# add session support later
      'category_name7'=>'',# add session support later
      'category_score7'=>'',# add session support later
      'category_name8'=>'',# add session support later
      'category_score8'=>'',# add session support later
      'is_valid'=>'',# add session support later
      'discuz_pid'=>'',# add session support later
      'priority'=>'10',# add session support later
      'grade'=>'',# add session support later
      'reject_reason'=>'',# add session support later
      'is_accept'=>'',# add session support later
      'is_publish'=>'',# add session support later
      );

    $h_feature = array(
      'mid' => 'search_int',
      'is_accept'        => array('ny:radio',        'is_accept',       ),
      'is_publish'       => array('ny:radio',        'is_publish',      ),
                 );

    $showsearch_data = $this->process_showsearch_feature($dbh_r, $h_feature, $h_default_value);
    $this->tmpl_assign('showsearch_data', $showsearch_data);

    $this->tmpl_assign('oid', $oid);
    
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('showsearch');
  }

  function clearsearch(){
  	$oid = $this->get_param('pq','oid', 0, 'int');
    
    $this->search_clear('cms_builder_product_reports#');
    return $this->cms_redirect_default_action(array('oid'=>$oid));
  }

  function action_search(){
    if (! $this->user_can('list') ) return $this->trap();
    #<!--START:__PSAUTH-->return $this->psauth_no_access() if (not $this->psauth_can_access('search'));<!--END:__PSAUTH-->

    $oid = $this->get_param('pq','oid', 0, 'int');
    
    $h_feature = array(
      
      );
    list ($flag, $a_condition) = $this->search_build_sql($h_feature);
    if ($flag == 1){
      return $this->errmsg('no_search_input', 2) ;
    }

    if (is_array($a_condition)  && !empty($a_condition)){
      $this->s_param('cms_builder_product_reports#'.'SEARCH_COND', $a_condition);
    }

    return $this->cms_redirect_default_action(array('oid'=>$oid));
  }

/**START:COPY**/

##COPY_TYPE_FUNC##
  function action_copy(){
    if (! $this->user_can('add') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    $oid = $this->get_param('pq','oid', 0, 'int');
    
    $dbh_w = $this->db_connect('write');

    $h_param = array(
    
                   );

    list($count, $new_id)=  $this->copy_row_by_key($dbh_w, $this->param('table'), 'id', $id, $h_param);
    #my ($count, $new_id) = $this->copy_row_by_key($dbh, $this->param('table'), 'id', $id, '', %feature);
    /**START:COPY_BY_FK_HAS_CHILD**/
    if ($this->q_param('subaction') == 'with_child'){
      #$this->##PS_SHARE_CHILD_MODULE_PREFIX##copy_by_parent_key($id, $new_id);
    }
    /**END:COPY_BY_FK_HAS_CHILD**/

    return  $this->action_edit($new_id);
  }

/**END:COPY**/

// Supplementary function add here

  // ajas update a field
  function ajax_update_field(){
    $id   = $this->get_q('id', 0, 'int');
    if ($id == 0) return 'invalid ID';

    ################################################
    # General update, common for all
    ################################################

    $dbh_w    = $this->db_connect('write');
    $h_feature = array();
    $changed = $this->update_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    if ($changed > 0){
      $row_affected = db_do($dbh_w, "update ".$this->param('table')." set lastmodify = NOW() where id =?", array($id)) ;
    }

    $dbh_r    = $this->db_connect('read');
    $field  = $this->q_param('#FIELD#');
    list ($value) = db_selectrow_array($dbh_r, "select $field from ".$this->param('table')." where id=?", array($id));
//    ### custom, change by type table
//    if ($field == 'aseip'){
//      list ($value) = db_selectrow_array($dbh, "select cname from test.dummy_type where id=?", array($value));
//    return $value;
//    }
//    #####

    return $value;

  }

/* Custom Class Function Implementation start here */

}//end class

$webapp = new cms_builder_product_reports(
   array('PARAMS' => array_merge($site_global_config, $local_config))
         );
$webapp->run();

/* Custom Helper Function Implementation start here */

?>
